<template>
    <popup
        title="调整训练组"
        :show="true"
        :loading="loading"
        :async-close="true"
        width="500px"
        @close="emits('close')"
        @confirm="handleSubmit"
    >
        <div class="p-6 pb-0">
            <el-form
                ref="formRef"
                label-width="100px"
                :model="formData"
                :rules="formRules"
                @submit.prevent
            >
                <el-form-item label="订阅数量">
                    {{ package }}（ 订阅套餐中的数量只能通过套餐调整 ）
                </el-form-item>
                <el-form-item label="当前数量">
                    {{ value }}（ 已使用 {{ usage }} 条训练组）
                </el-form-item>
                <el-form-item label="变更方式" required prop="action">
                    <el-radio-group v-model="formData.action">
                        <el-radio value="inc">增加</el-radio>
                        <el-radio value="dec">扣减</el-radio>
                        <el-radio value="final">最终</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="调整的数值" required prop="amount">
                    <el-input
                        v-model="formData.amount"
                        placeholder="请输入要变更的数值"
                        type="number"
                        :min="0"
                        :max="999999999"
                        @input="validateAndFormatInput"
                    />
                </el-form-item>
                <el-form-item :label="`调整后的值`">
                    {{ afterAdjustmentVal }}
                </el-form-item>
            </el-form>
        </div>
    </popup>
</template>

<script lang="ts" setup>
import type { FormInstance, FormRules } from 'element-plus'
import feedback from '@/utils/feedback'
import userApi from '@/api/users/user'

const emits = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()

const props = defineProps({
    user_id: {
        type: Number,
        default: 0
    },
    value: {
        type: [Number, String],
        required: true
    },
    usage: {
        type: [Number, String],
        required: true
    },
    package: {
        type: [Number, String],
        required: true
    }
})

// 表单数据
const loading = ref<boolean>(false)
const formData = reactive({
    user_id: 0,      // 用户ID
    scene: 'train',  // 操作场景
    action: 'inc',   // 变更方式: [inc=增加, dec=减少, final=最终]
    amount: ''       // 变更数值
})

// 表单规则
const formRules: FormRules = {
    amount: [
        {
            required: true,
            message: '请输入变更的数值'
        }
    ]
}

// 变动后的数值
const afterAdjustmentVal = computed(() => {
    switch (formData.action) {
        case 'inc':
            return Number(props.value) + Number(formData.amount)
        case 'dec':
            return Number(props.value) - Number(formData.amount)
        case 'final':
            return Number(formData.amount)
    }
})

/**
 * 校验表单数值
 */
const validateAndFormatInput = () => {
    const value = String(formData.amount).replace(/\D/g, '')
    if (value === '') {
        return
    }

    const numberValue = Number(value)
    if (numberValue < 0 || numberValue > 999999999) {
        if (numberValue < 0) {
            formData.amount = '0'
        } else {
            formData.amount = '999999999'
        }
    } else {
        formData.amount = String(numberValue)
    }
}

/**
 * 提交表单
 */
const handleSubmit = async () => {
    formData.scene = 'train'
    formData.user_id = props.user_id
    await formRef.value?.validate().then(async () => {
        loading.value = true
        await userApi.adjustAccount(formData)
            .finally(() => {
                loading.value = false
            })

        feedback.msgSuccess('调整成功')
        emits('close')
        emits('success')
    }).catch(() => {})
}
</script>
